package com.springboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.springboot.common.ResponseCode;
import com.springboot.common.Result;
import com.springboot.entity.Comment;
import com.springboot.entity.Order;
import com.springboot.entity.OrderItem;
import com.springboot.mapper.CommentMapper;
import com.springboot.mapper.ProductSpecColorMapper;
import com.springboot.mapper.ProductSpecSizeMapper;

import com.springboot.service.ICommentService;
import com.springboot.service.IOrderItemService;
import com.springboot.service.IOrderService;
import com.springboot.utils.IntegerUtils;
import com.springboot.utils.JwtTokenUtils;
import com.springboot.utils.PermissionUtils;
import com.springboot.vo.CommentVO;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * 商品评论表 服务实现类
 *
 * @author zjb
 * @since 2025-10-30
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService {

    @Resource
    private CommentMapper commentMapper;

    @Resource
    private IOrderService orderService;

    @Resource
    private IOrderItemService orderItemService;

    @Resource
    private ProductSpecColorMapper productSpecColorMapper;

    @Resource
    private ProductSpecSizeMapper productSpecSizeMapper;

    /**
     * 添加评论
     *
     * @param userId  用户ID
     * @param comment 评论信息
     * @return 添加结果
     */
    @Override
    public Result addComment(Integer userId, Comment comment) {
        // 参数校验
        if (IntegerUtils.isEmptyOrZero(comment.getProductId())) {
            return Result.error("商品ID不能为空");
        }

        if (comment.getRating() == null || comment.getRating() < 1 || comment.getRating() > 5) {
            return Result.error("评分必须在1-5之间");
        }

        if (comment.getContent() == null || comment.getContent().trim().isEmpty()) {
            return Result.error("评论内容不能为空");
        }
        if (!StringUtils.hasText(comment.getOrderId())) {
            return Result.error("关联订单id不能为空");
        }
        Order order = orderService.getOne(new LambdaQueryWrapper<Order>()
                .eq(Order::getOrderId, comment.getOrderId())
                .eq(Order::getUserId, userId));
        if (order == null) {
            return Result.error("用户与订单信息不匹配");
        }

        //根据orderId和productId查询order_item表
        List<OrderItem> orderItemList = orderItemService.list(new LambdaQueryWrapper<OrderItem>()
                .eq(OrderItem::getOrderId, comment.getOrderId())
                .eq(OrderItem::getProductId, comment.getProductId()));


        if (!Objects.equals(comment.getProductId(), orderItemList.get(0).getProductId())) {
            return Result.error("订单号与商品不符合");
        }
        // 设置评论信息
        comment.setSkuId(orderItemList.get(0).getSkuId());
        comment.setUserId(userId);
        comment.setStatus(1); // 默认显示
        comment.setCreateTime(LocalDateTime.now());

        // 保存评论
        if (save(comment)) {
            return Result.success("评论成功");
        } else {
            return Result.error("评论失败");
        }
    }

    /**
     * 查询所有评论
     *
     * @param pageNum  页码
     * @param pageSize 每页数量
     * @param search 搜索参数
     * @return 评论列表
     */
    @Override
    public Result getCommentAll(Integer pageNum, Integer pageSize,String search) {
        IPage<CommentVO> page = new Page<>(pageNum, pageSize);
        IPage<CommentVO> commentVOIPage = commentMapper.selectCommentAll(page,search);
        return Result.success(commentVOIPage, "查询成功");
    }

    /**
     * 根据商品ID获取评论列表
     *
     * @param productId 商品ID
     * @param pageNum   页码
     * @param pageSize  每页数量
     * @return 评论列表
     */
    @Override
    public Result getCommentsByProductId(Integer productId, Integer pageNum, Integer pageSize) {
        if (IntegerUtils.isEmptyOrZero(productId)) {
            return Result.error("商品ID不能为空");
        }

        if (pageNum == null || pageNum <= 0) {
            pageNum = 1;
        }

        if (pageSize == null || pageSize <= 0) {
            pageSize = 10;
        }

        IPage<CommentVO> page = new Page<>(pageNum, pageSize);

        IPage<CommentVO> commentVOIPage = commentMapper.selectCommentsByProductId(page, productId);


        return Result.success(commentVOIPage, "查询成功");
    }

    /**
     * 根据用户ID获取评论列表
     *
     * @param userId   用户ID
     * @param pageNum  页码
     * @param pageSize 每页数量
     * @return 评论列表
     */
    public Result getCommentsByUserId(Integer userId, Integer pageNum, Integer pageSize) {

        if (!PermissionUtils.IncludingAdministrators(userId)) {
            return Result.error(ResponseCode.FORBIDDEN, "不能查看他人信息");
        }
        if (IntegerUtils.isEmptyOrZero(userId)) {
            return Result.error("用户ID不能为空");
        }

        if (pageNum == null || pageNum <= 0) {
            pageNum = 1;
        }

        if (pageSize == null || pageSize <= 0) {
            pageSize = 10;
        }

        IPage<CommentVO> page = new Page<>(pageNum, pageSize);

        IPage<CommentVO> commentVOIPage = commentMapper.selectCommentsByUserId(page, userId);


        return Result.success(commentVOIPage, "查询成功");
    }

    /**
     * 删除评论
     *
     * @param userId    用户ID
     * @param commentId 评论ID
     * @return 删除结果
     */
    @Override
    public Result deleteComment(Integer userId, Integer commentId) {
        if (IntegerUtils.isEmptyOrZero(commentId)) {
            return Result.error("评论ID不能为空");
        }

        Comment comment = getById(commentId);
        if (comment == null) {
            return Result.error("评论不存在");
        }

        // 检查是否是自己的评论
        if (!userId.equals(comment.getUserId())) {
            return Result.error("只能删除自己的评论");
        }

        // 删除评论（软删除，设置状态为隐藏）
        comment.setStatus(0);
        if (updateById(comment)) {
            return Result.success("删除成功");
        } else {
            return Result.error("删除失败");
        }
    }

    /**
     * 批量删除评论
     *
     * @param commentIds 评论id数组
     * @return 删除结果
     */
    @Override
    @Transactional
    public Result deleteCommentBatch(List<Integer> commentIds) {
        if (CollectionUtils.isEmpty(commentIds)) {
            return Result.error("评论ID列表不能为空");
        }
        boolean result = removeByIds(commentIds);
        if (result) {
            return Result.success("批量删除成功");
        } else {
            return Result.error("批量删除失败");
        }
    }
}